package com.hc.java.thread;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * 解决死锁方案：
 * 1.锁粒度放大，比如锁筷子盒，里面包含5根筷子
 * 2.其中 有一个反着拿筷子
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/16 19:55
 */
public class 哲学家就餐 {
    public static void main(String[] args) {
        ChopStick c1 = new ChopStick();
        ChopStick c2 = new ChopStick();
        ChopStick c3 = new ChopStick();
        ChopStick c4 = new ChopStick();
        ChopStick c5 = new ChopStick();

        Philosohper p1 = new Philosohper("p1", 1, c1, c2);
        Philosohper p2 = new Philosohper("p2", 2, c2, c3);
        Philosohper p3 = new Philosohper("p3", 3, c3, c4);
        Philosohper p4 = new Philosohper("p4", 4, c4, c5);
        Philosohper p5 = new Philosohper("p5", 5, c5, c1);

//        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        p1.start();
        p2.start();
        p3.start();
        p4.start();
        p5.start();
    }
}

/**
 * 筷子
 */
class ChopStick {
}

/**
 * 哲学家
 */
@Getter
@Setter
@AllArgsConstructor
class Philosohper extends Thread {
    private String personName;
    private Integer index;
    private ChopStick left, right;

    @Override
    public void run() {
        // 解决死锁：某个人反着拿筷子
        if (index == 0) {
            synchronized (left) {
                System.out.println(personName + "拿到第一根筷子");
                synchronized (right) {
                    System.out.println(personName + "拿到第二根筷子");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(personName + "吃完了");
                }
            }
        } else {
            synchronized (right) {
                System.out.println(personName + "拿到第二根筷子");
                synchronized (left) {
                    System.out.println(personName + "拿到第一根筷子");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(personName + "吃完了");
                }
            }
        }
    }
}